package m202405.d16;

import java.util.Stack;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/5/17 09:51
 */
public class Q32 {

    public static void main(String[] args) {
        Q32 q32 = new Q32();
        q32.longestValidParentheses("((())");
        System.out.println();
    }

    /**
     * 将符合规则的()转换为0，判断最长连续0的长度
     */
    public int longestValidParentheses(String s) {
        int[] flag = new int[s.length()];
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            flag[i] = c == '(' ? -1 : 1;
        }
        find(s, s.length(), flag);
        int max = 0;
        int counter = 0;
        for (int i : flag) {
            if (i != 0) {
                max = Math.max(max, counter);
                counter = 0;
            } else {
                counter++;
            }
        }
        return Math.max(counter, max);
    }

    private void find(String s, int end, int[] flag) {
        Stack<Node> stack = new Stack<>();
        for (int i = 0; i < end; i++) {
            char c = s.charAt(i);
            if (c == '(') {
                stack.push(new Node(c, i));
            } else {
                if (stack.isEmpty()) {
                    continue;
                }
                Node pop = stack.pop();
                if (pop.c == '(') {
                    flag[pop.index] = 0;
                    flag[i] = 0;
                } else {
                    stack.clear();
                    return;
                }
            }
        }
    }

    private static class Node {
        char c;
        int index;

        public Node(char c, int index) {
            this.c = c;
            this.index = index;
        }
    }
}
